const http = require('http')
const url = require('url')
const items = [
  'test 0',
  'test 1'
]

const server = http.createServer((req, res) => {
  switch (req.method) {
    case 'POST':
      let item = ''
      req.setEncoding('utf8')
      req.on('data', (chunk) => {
        console.log('>>> data:', chunk)
        item += chunk
      })
      req.on('end', () => {
        console.log('<<< end:', item)
        items.push(item)
        res.end('OK\n')
      })
      break
    case 'GET':
      let body = '\n'
      body += items.map((item, i) => {
        return `${i}) ${item}`
      }).join('\n')
      res.setHeader('Content-Length', Buffer.byteLength(body))
      res.setHeader('Content-Type', 'text/plain; charset="utf-8"')
      console.log('<<< get', body)
      res.end(body)
      break
    case 'DELETE':
      const path = url.parse(req.url).pathname
      const i = parseInt(path.slice(1), 10)
      console.log('>>> delete', i)
      if (isNaN(i)) {
        res.statusCode = 400
        res.end('Invalid item id')
      } else if (!items[i]) {
        res.statusCode = 404
        res.end('Item not found')
      } else {
        items.splice(i, 1)
        res.end('OK\n')
      }
      break
    default:
      res.statusCode = 400
      res.end('Method not support')
  }
})
server.listen(3000, () => {
  console.log('HTTP server running in port: http://localhost:3000')
})

/*
curl -d 'buy groceries' http://localhost:3000
curl -d 'buy node in action' http://localhost:3000
curl http://localhost:3000
curl -X DELETE http://localhost:3000/1
 */
